import React from 'react';
import { View, Image, StyleSheet, TouchableOpacity, Dimensions, Platform, ViewStyle, ImageStyle, Text, ActivityIndicator } from 'react-native';
import { Video, ResizeMode } from 'expo-av';
import { Audio } from 'expo-av';
import { MaterialIcons } from '@expo/vector-icons';
import { ThemedView } from './ThemedView';
import { ThemedText } from './ThemedText';
import { useTheme } from './theme/ThemeContext';
import { ArtworkResponse } from '../utils/api/types';
import * as Linking from 'expo-linking';
import { useRouter, useFocusEffect } from 'expo-router';
import { getFullURL, addTimestamp } from '../utils/url';

const { width } = Dimensions.get('window');

interface ArtworkCardProps {
  artwork: ArtworkResponse;
  variant: 'featured' | 'recent';
}

// 文件类型图标映射
const FILE_TYPE_ICONS = {
  'image': 'image',
  'video': 'videocam',
  'audio': 'audiotrack',
  'text': 'description',
  'code': 'code',
  'application': 'insert-drive-file',
} as const;

export function ArtworkCard({ artwork, variant }: ArtworkCardProps) {
  const { theme } = useTheme();
  const router = useRouter();
  const [sound, setSound] = React.useState<Audio.Sound>();
  const [isPlaying, setIsPlaying] = React.useState(false);
  const [isVideoLoading, setIsVideoLoading] = React.useState(true);
  const videoRef = React.useRef<Video>(null);

  // 处理卡片点击
  const handleCardPress = () => {
    router.push({
      pathname: '/artwork/[id]',
      params: { id: artwork.id }
    });
  };

  // 处理音频播放
  async function handleAudioPlayback() {
    try {
      if (sound) {
        if (isPlaying) {
          await sound.pauseAsync();
          setIsPlaying(false);
        } else {
          await sound.playAsync();
          setIsPlaying(true);
        }
      } else {
        // 初始化音频系统
        await Audio.setAudioModeAsync({
          playsInSilentModeIOS: true,
          staysActiveInBackground: false,
          shouldDuckAndroid: true,
          playThroughEarpieceAndroid: false
        });

        // 加载并播放音频
        const { sound: newSound } = await Audio.Sound.createAsync(
          { uri: getFullURL(artwork.file_url) },
          { shouldPlay: true }
        );
        
        // 监听播放完成事件
        newSound.setOnPlaybackStatusUpdate((status) => {
          if (status.isLoaded) {
            if (status.didJustFinish) {
              setIsPlaying(false);
            }
          }
        });

        setSound(newSound);
        setIsPlaying(true);
      }
    } catch (error) {
      console.error('音频播放错误:', error);
      // 重置状态
      setIsPlaying(false);
      if (sound) {
        await sound.unloadAsync();
        setSound(undefined);
      }
    }
  }

  // 页面焦点变化时暂停媒体播放
  useFocusEffect(
    React.useCallback(() => {
      return () => {
        if (sound) {
          sound.pauseAsync();
          setIsPlaying(false);
        }
      };
    }, [sound])
  );

  // 页面卸载时清理资源
  React.useEffect(() => {
    return () => {
      if (sound) {
        sound.unloadAsync();
        setSound(undefined);
        setIsPlaying(false);
      }
    };
  }, [sound]);

  // 处理文件下载
  const handleFileDownload = () => {
    const url = addTimestamp(getFullURL(artwork.file_url));
    Linking.openURL(url);
  };

  // 获取文件类型图标
  const getFileTypeIcon = (fileType: string) => {
    const type = fileType.split('/')[0];
    return FILE_TYPE_ICONS[type as keyof typeof FILE_TYPE_ICONS] || 'insert-drive-file';
  };

  // 处理视频加载完成
  const handleVideoLoad = () => {
    setIsVideoLoading(false);
  };

  // 处理视频错误
  const handleVideoError = (error: any) => {
    console.error('Video loading error:', error);
    setIsVideoLoading(false);
  };

  // 根据文件类型渲染不同的内容
  const renderContent = () => {
    const fileUrl = artwork.file_url;
    const fileType = artwork.file_type.split('/')[0];

    switch (fileType) {
      case 'image':
        return (
          <View style={styles.mediaContainer}>
            <Image
              source={{ uri: fileUrl }}
              style={styles.mediaImage}
              resizeMode="cover"
            />
          </View>
        );

      case 'video':
        return (
          <View style={styles.mediaContainer}>
            <Video
              ref={videoRef}
              source={{ 
                uri: fileUrl,
                headers: {
                  'Accept': 'video/*',
                  'Cache-Control': 'no-cache'
                }
              }}
              style={styles.media}
              useNativeControls={false}
              resizeMode={ResizeMode.COVER}
              shouldPlay={false}
              isLooping={true}
              onLoad={handleVideoLoad}
              onError={(error) => {
                console.error('视频加载错误:', error, fileUrl);
                handleVideoError(error);
              }}
            />
            <View style={[styles.overlay, isVideoLoading && styles.loadingOverlay]}>
              {isVideoLoading ? (
                <View style={styles.loadingContainer}>
                  <ActivityIndicator size="large" color="white" />
                  <Text style={styles.loadingText}>视频加载中...</Text>
                </View>
              ) : (
                <TouchableOpacity 
                  style={styles.videoControls}
                  onPress={() => {
                    if (videoRef.current) {
                      videoRef.current.presentFullscreenPlayer();
                    }
                  }}
                >
                  <MaterialIcons name="play-circle-filled" size={48} color="white" />
                  <Text style={styles.videoText}>点击播放视频</Text>
                </TouchableOpacity>
              )}
            </View>
          </View>
        );

      case 'audio':
        return (
          <TouchableOpacity 
            style={styles.audioContainer} 
            onPress={handleAudioPlayback}
          >
            <MaterialIcons
              name={isPlaying ? 'pause-circle-filled' : 'play-circle-filled'}
              size={48}
              color={theme.colors.primary}
            />
            <ThemedText variant="caption" style={styles.audioText}>
              {isPlaying ? '暂停' : '播放'}音频
            </ThemedText>
          </TouchableOpacity>
        );

      case 'text':
      case 'code':
        return (
          <View style={styles.textContainer}>
            <MaterialIcons
              name={getFileTypeIcon(artwork.file_type)}
              size={32}
              color={theme.colors.primary}
            />
            <ThemedText variant="body" style={styles.description}>
              {artwork.description || '点击查看详情'}
            </ThemedText>
          </View>
        );

      default:
        return (
          <TouchableOpacity 
            style={styles.fileContainer} 
            onPress={handleFileDownload}
          >
            <MaterialIcons
              name={getFileTypeIcon(artwork.file_type)}
              size={32}
              color={theme.colors.primary}
            />
            <ThemedText variant="caption" style={styles.fileText}>
              查看文件
            </ThemedText>
          </TouchableOpacity>
        );
    }
  };

  const cardStyle = React.useMemo(() => {
    const baseStyle = variant === 'featured' ? styles.featuredCard : styles.recentCard;
    return Platform.select({
      web: {
        ...baseStyle,
        overflow: 'hidden' as const,
      },
      default: baseStyle,
    }) as ViewStyle;
  }, [variant]);

  return (
    <TouchableOpacity onPress={handleCardPress}>
      <ThemedView
        variant="card"
        style={cardStyle}
      >
        <ThemedText variant="body" style={styles.title}>
          {artwork.title}
        </ThemedText>
        {renderContent()}
        {artwork.tags && artwork.tags.length > 0 && (
          <View style={styles.tagsContainer}>
            {artwork.tags.slice(0, 2).map((tag, index) => (
              <View
                key={index}
                style={[styles.tag, { backgroundColor: theme.colors.primary + '20' }]}
              >
                <Text style={[styles.tagText, { color: theme.colors.primary }]}>
                  {tag}
                </Text>
              </View>
            ))}
            {artwork.tags.length > 2 && (
              <Text style={[styles.moreText, { color: theme.colors.placeholder }]}>
                +{artwork.tags.length - 2}
              </Text>
            )}
          </View>
        )}
      </ThemedView>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  featuredCard: {
    width: Platform.OS === 'web' ? `${(width * 0.8)}px` : width * 0.8,
    height: 200,
    marginRight: 16,
    padding: 16,
    borderRadius: 12,
  } as ViewStyle,
  recentCard: {
    width: Platform.OS === 'web' ? `${((width - 48) / 2)}px` : (width - 48) / 2,
    height: 160,
    marginBottom: 16,
    padding: 12,
    borderRadius: 8,
  } as ViewStyle,
  title: {
    marginBottom: 8,
    fontWeight: 'bold',
  },
  mediaContainer: {
    flex: 1,
    borderRadius: 8,
    overflow: 'hidden',
    position: 'relative',
  } as ViewStyle,
  media: {
    width: '100%',
    height: '100%',
  } as ViewStyle,
  mediaImage: {
    width: '100%',
    height: '100%',
    resizeMode: 'cover',
  } as ImageStyle,
  overlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0, 0, 0, 0.4)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  videoControls: {
    alignItems: 'center',
  },
  videoText: {
    color: 'white',
    marginTop: 8,
    fontSize: 14,
    textShadowColor: 'rgba(0, 0, 0, 0.75)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 3,
  },
  audioContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  audioText: {
    marginTop: 8,
    textAlign: 'center',
  },
  textContainer: {
    flex: 1,
    padding: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  description: {
    marginTop: 8,
    textAlign: 'center',
    fontSize: 14,
    lineHeight: 20,
  },
  fileContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  fileText: {
    marginTop: 8,
    textAlign: 'center',
  },
  tagsContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 8,
    gap: 8,
  },
  tag: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
  },
  tagText: {
    fontSize: 12,
  },
  moreText: {
    fontSize: 12,
  },
  loadingOverlay: {
    backgroundColor: 'rgba(0, 0, 0, 0.6)',
  },
  loadingContainer: {
    alignItems: 'center',
  },
  loadingText: {
    color: 'white',
    marginTop: 8,
    fontSize: 14,
    textShadowColor: 'rgba(0, 0, 0, 0.75)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 3,
  },
}); 